<template lang="pug">
    view(class="task-details flex" @click="closeAddItemBar")
        scroll-view(scroll-y="true" id="scrollView" :style="[{ height: scrollHeight+'px' }]")
            <!--导航栏-->
            CuCustom(bgColor="bg-gradual-pink" :isBack="true")
                block(slot="content") 任务清单

            view(class="flex-sub task-details-body padding-sm")
                <!--任务信息-->
                view(class="cu-bar bg-white solid-bottom")
                    view(class="action")
                        text(class="cuIcon-titles text-orange")
                        text(class="text-black text-xl text-bold") {{ task.task_name }}
                    view(class="action")
                        template(v-if="status === states.deleting")
                            text(class="text-black" @click="status = states.default") 完成
                        template(v-else)
                            text(class="text-black" @click="status = states.deleting") 管理
                        text(class="cuIcon-moreandroid margin-left" @click="more_visible=true")
                view(class="cu-list menu text-left bg-white margin-bottom-xl shadow shadow-lg sm-border")
                    <!--待办列表-->
                    view(class="cu-item" v-for="item in task.items" :key="item.id" v-if="!item.is_done || display_has_done_item")
                            view(class="content")
                                text(class="text-blue text-xl" v-if="status !== states.deleting" @click="radioClick(item)" :class="item.is_done ? 'cuIcon-roundcheckfill' : 'cuIcon-round'")
                                text(@click="radioClick(item)" :class="item.is_done? 'text-through' : ''") {{ item.content }}
                            
                            view(class="action")
                                text(class="text-blue text-xl" v-if="status === states.deleting" 
                                        @click="checkedClick(item)" 
                                        :class="item.checked ? 'cuIcon-roundcheckfill' : 'cuIcon-round'")
                <!--辅助空白-->
                view(class="padding-bottom-xl")
                view(class="padding-bottom-xl")
            
        <!--添加项表单-->
        view(v-if="add_bar_visible" class="cu-bar foot input" :style="{ bottom: `${add_bar_input_bottom}px` }" @click.stop)
            view(class="action") 
                text(class="cuIcon-round text-grey")
            input(cursor-spacing="100" class="solid-bottom"
                  :adjust-position="false" @confirm="addTaskItem"
                  :focus="true" maxlength="300"
                  @blur="inputBlur" @focus="onFocus"
                  :confirm-hold="true" v-model="item_content")
            button(class="cu-btn bg-green shadow" @click="addTaskItem") 添加 
        
        view(class="cu-bar foot bg-white" v-if="status === states.deleting")
            view(class="action")
            view(class="action")
                button(class="cu-button bg-orange sm" @click="requestDelete") 删除 
            
        
        <!--添加项按钮-->
        view(v-if="add_item_button_visible" class="text-xsl text-red add-button" @click.stop)
            text(class="cuIcon-roundaddfill shadow" @click.stop="status = states.adding")
        
        <!--新建任务-->
        new-task(@task-created="taskCreated")
        view(class="cu-modal bottom-modal" :class="more_visible ? 'show' : ''")
            view(class="cu-dialog")
                view(class="cu-bar bg-white")
                    view(class="action text-blue" @click="more_visible=false") 取消
                
                view(class="padding-xl")
                    button(class="bg-red text-white" @click="confirm_visible=true") 删除任务
                    button(class="margin-top bg-white text-black" @click="task_share_visible=true") 生成分享链接
                    button(class="margin-top bg-blue text-white" 
                            v-if="display_has_done_item"
                            @click="hideHasDoneItems") 隐藏完成项
                    button(v-else class="margin-top bg-blue text-white" 
                            @click="displayHasDoneItems") 显示完成项
        Modal(:visible.sync="confirm_visible" title="删除待办任务" @submit="deleteTask")
                    text(class="text-red") 确定要删除这个任务吗?
        TaskShare(:task="task" :visible.sync="task_share_visible" @share-btn-click="more_visible=false")
    
</template>

<script>
import NewTask from "./new-task.vue";
import BaseMixin from "../../mixins/BaseMixin.js";
import uniList from "../../components/uni-list/uni-list.vue";
import uniListItem from "../../components/uni-list-item/uni-list-item.vue";
import uniIcons from "../../components/uni-icons/uni-icons.vue";
import TaskItemList from "./task-item-list";
import Modal from "../../components/colorui/modal.vue";
import TaskShare from "./task-share.vue";

const states = {
  default: 0, // 默认状态
  deleting: 1, // 选择删除
  adding: 2 // 显示添加栏
};

export default {
  components: {
    NewTask,
    uniList,
    uniListItem,
    uniIcons,
    TaskItemList,
    Modal,
    TaskShare
  },

  mixins: [BaseMixin],

  data() {
    return {
      task: { name: "", items: [] },

      task_items: [],

      done_item_ids: [],

      item_content: "",

      add_bar_input_focus: false, // 添加栏输入焦点
      add_bar_input_bottom: 0, // 输入框的bottom高设置，以解决拉起输入法输入框被遮挡问题

      scrollHeight: 0,

      states: states, // 状态可选项
      status: states.default, // 状态

      more_visible: false, // 更多操作面板是否可视

      confirm_visible: false, // 删除任务

      has_init: false,

      task_share_visible: false, // 分享面板展示
    };
  },

  computed: {
    tasks() {
      return this.$store.state.todo.tasks || [];
    },

    task_id() {
      return this.$store.state.todo.task_id;
    },

    add_bar_visible() {
      return this.status === this.states.adding;
    },

    add_item_button_visible() {
      return this.status === this.states.default;
    },

    deleted_count() {
      return this.task.items.filter(item => item.is_deleted).length;
    },

    // 是否显示已完成的待办项
    display_has_done_item() {
      const task_ids =
        this.$store.state.todo.undisply_has_done_items_tasklist || [];
      return task_ids.indexOf(this.task_id) === -1;
    }
  },

  watch: {
    task_id() {
      if (this.has_init) this.get_task();
    },

    status(status) {
      switch (status) {
        case states.adding:
          this.add_bar_input_focus = true;
          break;
        default:
          this.add_bar_input_focus = false;
      }
    }
  },

  methods: {
    get_task() {
      if (!this.task_id) return;
      // 尝试从本地获取任务
      // 失败再从服务器获取数据
      var task = this.tasks.find(task => task.id == this.task_id);
      if (task) {
        this.updateLocalTask(task);
        return;
      }

      this.get(`/todo_tasks/${this.task_id}`).then(task => {
        this.updateLocalTask(task);
      });
    },

    updateLocalTask(task) {
      this.task = task;
      uni.setNavigationBarTitle({ title: task.task_name });
    },

    addTaskItem() {
      if (!this.item_content) return;

      const taskItem = {
        task_id: this.task.id,
        content: this.item_content,
        is_done: false
      };
      this.item_content = "";
      this.post("/todo_items/", taskItem).then(task => {
        this.task.items.push(task);
        this.$store.dispatch("todo/update_task", task);

        // this.item_content = '';
        this.scrollToBottom();
      });

      this.add_bar_input_focus = true;
    },

    taskCreated(task) {
      this.$store.dispatch("todo/add_task", task);
      uni.setNavigationBarTitle({ title: task.task_name });
    },

    radioClick(item) {
      item.is_done = !item.is_done;
      this.put(`/todo_items/${item.id}/`, item).then(res => {}); // 更新服务器数据
      this.$forceUpdate();
    },

    inputBlur() {
      // this.add_bar_visible = false;
      this.add_bar_input_bottom = 0;
    },

    closeAddItemBar() {
      this.add_bar_input_focus = false;
      // this.status = this.states.default;
      return false;
    },

    scrollToBottom() {
      this.$nextTick(() => {
        uni.pageScrollTo({ scrollTop: 10000, duration: 300 });
      });
    },

    updateDeleted(item) {
      this.$set(item, "is_deleted", !item.is_deleted);
    },

    requestDelete() {
      const items = this.task.items.filter(item => item.checked);
      const itemIds = items.map(item => item.id);
      if (itemIds.length === 0) {
        this.status = this.states.default;
        return;
      }

      this.delete(`/todo_items/multiple?id=${itemIds.join(",")}`)
        .then(data => {
          this.removeItemsByIds(itemIds);
          this.$store.dispatch("todo/update_task", this.task);
        })
        .catch(() => {})
        .then(() => {});
    },

    removeItemsByIds(ids) {
      function removeItemBy(id) {
        const index = this.task.items.findIndex(item => item.id === id);
        if (index > -1) this.task.items.splice(index, 1);
      }

      ids.forEach(removeItemBy.bind(this));
    },

    onFocus(e) {
      const detail = e.detail;

      // this.$forceUpdate();
    },

    checkedClick(item) {
      this.$set(item, "checked", !item.checked);
      this.$forceUpdate();
    },

    hideHasDoneItems() {
      this.$store.dispatch(
        "todo/add_undisply_has_done_items_tasklist",
        this.task
      );
      this.more_visible = false;
    },

    displayHasDoneItems() {
      this.$store.dispatch(
        "todo/remove_undisply_has_done_items_tasklist",
        this.task
      );
      this.more_visible = false;
    },

    deleteTask() {
      const url = `/todo_tasks/multiple?id=${this.task.id}`;

      this.delete(url).then(res => {
        const options = { url: "/pages/index/index" };
        uni.redirectTo(options);
      });
    }
  },

  onShareAppMessage(res) {
    let that = this;
    if (res.from === "button" && res.target.id === "share-task") {
      // 来自页面内分享按钮
      return {
        title: `Hi~一起来编辑这个待办吧:${this.taks.task_name}`,
        path: `pages/task-item/task-share-accept?task_id=${this.task.id}`,
        imageUrl: null
      };
    }
  },

  onLoad(option) {
    if (!this.has_init) this.get_task(); // 不会触发watch
    //option为object类型，会序列化上个页面传递的参数
    this.$store.dispatch("todo/set_task_id", option.id || null);
    // 测试
    // this.$store.dispatch("todo/set_task_id", 3);
    // this.get_task();

    // 设置scroll高度
    const res = uni.getSystemInfoSync();

    const windowHeight = res.windowHeight;
    this.scrollHeight = windowHeight;

    const vm = this;
    uni.onKeyboardHeightChange(res => {
      vm.add_bar_input_bottom = res.height;
      vm.scrollHeight = windowHeight - res.height;
      vm.scrollToBottom();
    });
    this.has_init = true;
    setTimeout(() => {
      console.log(vm.task);
    }, 1000);
  }
};
</script>

<style scoped lang="scss">
.task-details {
  // background-color: #0081ff;
  min-height: 100vh;
  flex-direction: column;

  /**添加待办项按钮**/
  .add-button {
    position: fixed;
    bottom: 10px;
    right: 20px;

    text {
      background-color: white;
      border-radius: 50%;
    }
  }

  .text-through {
    text-decoration: line-through;
  }
}
</style>
